﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using DuJianliang.ApplicationPlatform.Common;
using DuJianliang.ApplicationPlatform.UserPermission;

namespace DuJianliang.ApplicationPlatform.Outbound
{
    public partial class OutboundEdit : System.Web.UI.Page
    {
        OutboundDal dal = new OutboundDal();

        private string FlowInstanceID
        {
            get
            {
                if (ViewState["FlowInstanceID"] != null)
                {
                    return ViewState["FlowInstanceID"].ToString();
                }
                else
                {
                    string flowInstanceID = Guid.NewGuid().ToString();
                    ViewState["FlowInstanceID"] = flowInstanceID;
                    return flowInstanceID;
                }
            }
            set
            {
                ViewState["FlowInstanceID"] = value;
            }
        }

        private string Source
        {
            get
            {
                object obj = ViewState["Source"];
                return obj != null ? obj.ToString() : string.Empty;
            }
            set
            {
                ViewState["Source"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.FlowInstanceID = Request.QueryString["FlowInstanceID"];
                this.Source = Request.QueryString["Source"];

                string url = "OutboundDetailEdit.aspx?FlowInstanceID=" + this.FlowInstanceID;
                btnAdd.Attributes.Add("onclick", string.Format("showPage('{0}','800px','600px');", url));

                BindGrid();

                InitControlData();
                SetControlState();
            }
        }

        private void InitControlData()
        {
            string sql = @"SELECT * FROM t5715_Outbound WHERE FlowInstanceID = @FlowInstanceID";

            Database database = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = database.GetSqlStringCommand(sql);
            database.AddInParameter(dbCommand, "@FlowInstanceID", DbType.String, this.FlowInstanceID);
            DataTable dataTable = database.ExecuteDataSet(dbCommand).Tables[0];

            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                lblCode.Text = dataTable.Rows[0]["Code"].ToString();
                
                DateTime date = new DateTime();
                if (DateTime.TryParse(dataTable.Rows[0]["CreateDate"].ToString(), out date))
                {
                    lblDate.Text = date.ToShortDateString();
                }

                txtOutboundBy.Text = dataTable.Rows[0]["OutboundBy"].ToString();
                txtToUnit.Text = dataTable.Rows[0]["ToUnit"].ToString();

                btnOK.Visible = false;
            }
            else
            {
                lblCode.Text = dal.CreateApplyCode();
                lblDate.Text = DateTime.Now.ToShortDateString();
                btnOK.Visible = true;
            }
        }

        private void SetControlState()
        {
            bool hasFlowData = false;
            bool flowCompleted = false;
            bool currentFlowStepIsFirstSetp = false;
            string flowEndOperation = string.Empty;

            if (!this.Source.ToLower().Equals("list"))
            {
                btnAdd.Visible = false;
                btnOK.Visible = false;
                btnReturn.Visible = false;
                gridView.Columns[5].Visible = false;
                return;
            }

            DataTable flowInstanceData = FlowHelper.GetFlowInstanceInfo(new Guid(this.FlowInstanceID));
            if (flowInstanceData != null && flowInstanceData.Rows.Count > 0)
            {
                currentFlowStepIsFirstSetp = FlowHelper.CurrentFlowStepIsFirstSetp(flowInstanceData.Rows[0]["FlowID"].ToString()
                    , this.FlowInstanceID);

                hasFlowData = true;

                if (flowInstanceData.Rows[0]["Completed"] != null)
                {
                    string strCompleted = flowInstanceData.Rows[0]["Completed"].ToString();

                    if (bool.TryParse(strCompleted, out flowCompleted) && flowCompleted)
                    {
                        if (flowInstanceData.Rows[0]["OperationID"] != null)
                        {
                            flowEndOperation = flowInstanceData.Rows[0]["OperationID"].ToString();
                        }
                    }
                }
            }

            if ((hasFlowData && !currentFlowStepIsFirstSetp))
            {
                btnAdd.Visible = false;
                gridView.Columns[5].Visible = false;
            }
            else
            {
                btnAdd.Visible = !btnOK.Visible;
                gridView.Columns[5].Visible = true;
            }
        }

        private void BindGrid()
        {
            string sql = @"SELECT * FROM t5715_OutboundDetail WHERE FlowInstanceID = @FlowInstanceID";

            Database database = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = database.GetSqlStringCommand(sql);
            database.AddInParameter(dbCommand, "@FlowInstanceID", DbType.String, this.FlowInstanceID);
            DataTable dataTable = database.ExecuteDataSet(dbCommand).Tables[0];
            gridView.DataSource = dataTable;
            gridView.DataBind();
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            string sql = @"INSERT INTO dbo.t5715_Outbound
                                   ([FlowInstanceID]
                                   ,[Code]
                                   ,[OutboundBy]
                                   ,[ToUnit]
                                   ,[CreateUser]
                                   ,[CreateDate])
                             VALUES
                                   (@FlowInstanceID
                                   ,@Code
                                   ,@OutboundBy
                                   ,@ToUnit
                                   ,@CreateUser
                                   ,GETDATE())";

            Database database = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = database.GetSqlStringCommand(sql);
            database.AddInParameter(dbCommand, "@FlowInstanceID", DbType.String, this.FlowInstanceID);
            database.AddInParameter(dbCommand, "@Code", DbType.String, lblCode.Text);
            database.AddInParameter(dbCommand, "@OutboundBy", DbType.String, txtOutboundBy.Text);
            database.AddInParameter(dbCommand, "@ToUnit", DbType.String, txtToUnit.Text);
            database.AddInParameter(dbCommand, "@CreateUser", DbType.String, CurrentInfo.Instance.CurrentUser.UserName);
            database.ExecuteNonQuery(dbCommand);

            InitControlData();
            SetControlState();

        }

        protected void gridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "del":
                    Delete(e.CommandArgument.ToString());
                    BindGrid();
                    break;
            }
        }

        private void Delete(string id)
        {
            string sql = @"DELETE FROM t5715_OutboundDetail WHERE ID = @ID";

            Database database = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = database.GetSqlStringCommand(sql);
            database.AddInParameter(dbCommand, "@ID", DbType.String, id);
            database.ExecuteNonQuery(dbCommand);
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            BindGrid();
        }

        protected void btnReturn_Click(object sender, EventArgs e)
        {
            Response.Redirect("OutboundList.aspx");
        }
    }
}